package pers.hubb.controller.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;
import pers.hubb.controller.UserController;
import pers.hubb.entity.user.UserEntity;
import pers.hubb.facade.user.UserService;
import pers.hubb.redis.RedisServiceTemp;
import pers.hubb.req.user.LoginReq;
import pers.hubb.rsp.Result;
import pers.hubb.utils.KeyGenerator;
import pers.hubb.utils.RedisPrefixUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hubb
 * @Description
 * @Date 2018/4/2 23:53
 */
@RestController
public class UserControllerImpl implements UserController {

	@Reference(version = "1.0.0")
	private UserService userService;

	/**
	 * HTTP Response中Session ID 的名字
	 */
	@Value("${session.SessionIdName}")
	private String sessionIdName;

	@Override
	public Result login(LoginReq loginReq, HttpServletResponse httpRsp) {
		// 登录鉴权
		UserEntity userEntity = userService.login(loginReq);
		// 登录成功
		doLoginSuccess(userEntity, httpRsp);
		return Result.newSuccessResult(userEntity);
	}

	/**
	 * 处理登录成功
	 *
	 * @param userEntity 用户信息
	 * @param httpRsp    HTTP响应参数
	 */
	private void doLoginSuccess(UserEntity userEntity, HttpServletResponse httpRsp) {
		// 生成SessionID
		String sessionID = RedisPrefixUtil.SESSIONID_PREFIX + KeyGenerator.getKey();

		// 将 SessionID-UserEntity 存入Redis
		// TODO 暂时存储本地
		RedisServiceTemp.userMap.put(sessionID, userEntity);

		// 将SessionID存入HTTP响应头
		Cookie cookie = new Cookie(sessionIdName, sessionID);
		httpRsp.addCookie(cookie);
	}
}
